package com.example.codegenerator.util;

import java.io.*;
import java.util.*;

public class FileUtils {

    public static List<Map<String, String>> getIds(String metaDataPath, String tableName) {
        List<Map<String, String>> list = getMetaData(metaDataPath, tableName);
        List<Map<String, String>> list1 = new ArrayList<>();
        for (Map<String, String> map : list) {
            if("PRI".equalsIgnoreCase(map.get("column_key"))) {
                list1.add(map);
            }
        }
        return list1;
    }

    public static void main(String[] args) {
        String metaDataPath = "D:/table_schema.txt";
        String tableName1 = "app_feedback";
        System.out.println(getMetaData(metaDataPath, tableName1));
        System.out.println(getIds(metaDataPath, tableName1));
    }

    public static List<Map<String, String>> getMetaData(String metaDataPath, String tableName) {
        File file = new File(metaDataPath);
        List<Map<String, String>> list = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine()) != null){
                if(line.toUpperCase().startsWith(tableName.toUpperCase() + "\t")) {
                    Map<String, String> map = new HashMap<>();
                    String[] cols = line.split("\t");
                    map.put("column_name", cols[1].trim());
                    map.put("column_type", cols[2].trim());
                    map.put("column_key", cols[3].trim());
                    map.put("column_comment", cols.length > 4? cols[4].trim():"");
                    list.add(map);
                }
                if(line.toUpperCase().startsWith("| " + tableName.toUpperCase() + " ")) {
                    String line1 = line.substring(1);
                    Map<String, String> map = new HashMap<>();
                    String[] cols = line1.split("\\|");
                    map.put("column_name", cols[1].trim());
                    map.put("column_type", cols[2].trim());
                    map.put("column_key", cols[3].trim());
                    map.put("column_comment", cols.length > 4? cols[4].trim():"");
                    list.add(map);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    public static void writeContentToFile(File file, String content) {
        if(!file.exists()) {
            try {
                System.out.println("新建文件状态：" + file.createNewFile());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
            fileOutputStream.write(content.getBytes());
            fileOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
